<?php

class Service_DT extends Service implements IService
{
    
    static $moduleName = 'Digital-Tunes Parser';
    static $author = 'KnKill';
    static $version = '1.00';
    static $site = 'digital-tunes.net';
    static $mask = '.*digital-tunes.net\/releases.*';
    static $metaFields = array(
        META_LABEL,
        META_GENRES,
        META_RELEASE_DATE,
        META_CATALOG
    );
    
    private $content;
    
    public function __construct($url) {
        $this->content = getPage($url);
        phpQuery::newDocumentHTML($this->content);
    }

    
    /**
     * getReleaseArtists
     */
    public function getReleaseArtists() {
        $artists = array();
        foreach(pq('.artist-full') as $artist) {
            $artists[] = pq($artist)->eq(0)->text();
        }
        return $artists;
    }
    
    
    /**
     * getReleaseTtitle
     */
    public function getReleaseTitle() {
        $title = trim(pq('.release-full')->eq(0)->text());
        return $title;
    }
    
    
    /**
     * getGenres
     */
    public function getGenres() {
        $genres = array();
        foreach(pq('#release-details')->contents()->eq(5)->find('a') as $genre) {
            $genres[] = pq($genre)->text();
        }
        return $genres;
    }
    
    
    /**
     * getLabel
     */
    public function getLabel() {
        $label = pq('.label')->eq(0)->text();
        return trim($label);
    }
    
    
    /**
     * getCatalog
     */
    public function getCatalog() {
        $catalog = pq('#release-details')->contents()->eq(7)->text();
        return trim($catalog);
    }
    
    
    /**
     * getReleaseDate
     */
    public function getReleaseDate() {
        $rd = pq('#release-details')->contents()->eq(3)->text();
        return trim($rd);
    }
    
    
    /**
     * getTracklist
     */
    public function getTracklist() {
        $tracklist = array();
        $index = 0;
        foreach(pq('.track-title') as $track) {
            $artists = array();
            $artistsObj = pq($track)->find('a.artist-medium');
            if (count($artistsObj) != 0) {;
                foreach($artistsObj as $artist) {
                    $artists[] = trim(pq($artist)->text());
                }
            } else {
                $artists = $this->getReleaseArtists();
            }
            pq($track)->children()->remove();
            
            preg_match('/(.*) \(([0-9]{1,}:[0-9]{2})\)/', pq($track)->text(), $data);
            $title = str_replace('-', '', $data[1]);
            $title = trim(str_replace('&amp;', '&', $title));
            $length = trim($data[2]);
            $tracklist[(int)++$index] = array(
                'artists' => $artists,
                'title'   => $title,
                'length'  => $length
            );
        }
        return $tracklist;
    }

}